10. Exercise: Lambdas

Calculator

In this exercise, you will build on your last exercise to make a simple, general-purpose calculator program that can be run from the command-line to perform math on two integer operands

In case you need to brush up on the jargon: in the expression 1 + 2, + is known as the operator, and 1 and 2 are known as the operands).

The Calculator API should roughly look like this:

Calculator calculator = new Calculator();
calculator.registerOperation("+", (a, b) -> a + b);
assert 5 == calculator.calculate(2, "+", 3);

The main file, Calculate.java has already been partially filled in to parse the int operands and the String operator from the command-line arguments. Your task is to:

  1. Fill in the Calculator class, which has been left completely empty in the starter code; and
  2. Modify the main() method in Calculate.java to register the four "basic" binary operations:
    • Addition (represented by the "+" symbol)
    • Subtraction (represented by the "-" symbol)
    • Multiplication (represented by the "*" symbol)
    • Division (represented by the "/" symbol)

The Calculator class should maintain a mapping of operator symbols, such as "+", to operations. The operations will be represented by lambdas (see the code example above) that target a certain Functional Interface. We saw this in the previous code snippet:

calculator.registerOperation("+", (a, b) -> a + b);

If you need a reminder about what built-in functional interface you can use for this part, reread the solution page for the previous exercise.

After you have finished, you should be able to use the Calculate program like this:

javac Calculate.java
java Calculate 3 + 4
7
java Calculate 48 / 8
6

Pretty nifty, huh?

TODO List

Task List:

Task Feedback:

Nice work! You used lambdas to implement a calculator!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin